package com.suishoupai.xmb.controller;

import com.github.pagehelper.Page;
import com.suishoupai.xmb.entity.AjaxMessage;
import com.suishoupai.xmb.entity.SaleXiaoqu;
import com.suishoupai.xmb.service.SaleXiaoquService;
import com.suishoupai.xmb.service.XiaoquService;
import com.suishoupai.xmb.utils.PageUtil;
import com.suishoupai.xmb.utils.SecurityUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Created by caojian on 2017/4/6.
 */
@Controller
@RequestMapping("/sale/xiaoqu")
@PreAuthorize("hasRole('ROLE_SALE')")
public class SaleXiaoquController {
    @Autowired
    private XiaoquService xiaoquService;
    @Autowired
    private SaleXiaoquService saleXiaoquService;

    /**
     * 商家的服务小区列表
     *
     * @return
     */
    @GetMapping("")
    public Object index(@RequestParam Map map, Model model) {
        long saleId = SecurityUserUtil.getUser().getId();
        PageUtil.startPage(map);
        Page page = (Page) saleXiaoquService.getListBySaleId(saleId);
        model.addAttribute("xiaoquList", page.toPageInfo());
        return "sale-xiaoqu-list";
    }

    /**
     * 商家添加服务小区页面
     *
     * @return
     */
    @GetMapping("/add")
    public Object addPage(@RequestParam Map map, Model model) {
        PageUtil.startPage(map);
        Page page = (Page) xiaoquService.getAll();
        model.addAttribute("xiaoquList", page.toPageInfo());
        return "sale-xiaoqu-add";
    }

    /**
     * 商家添加服务小区
     *
     * @param xiaoquId
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Object add(long xiaoquId) {
        long saleId = SecurityUserUtil.getUser().getId();
        if (saleXiaoquService.hasSaleXiaoqu(xiaoquId, saleId)) {
            return AjaxMessage.newErrorHintMsg("该小区已添加过了。");
        }
        SaleXiaoqu saleXiaoqu = new SaleXiaoqu();
        saleXiaoqu.setXiaoquId(xiaoquId);
        saleXiaoqu.setSaleId(saleId);
        saleXiaoquService.add(saleXiaoqu);
        return AjaxMessage.newSuccessMsg();
    }

    /**
     * 商家移除服务小区
     *
     * @param xiaoquId
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(long xiaoquId) {
        long saleId = SecurityUserUtil.getUser().getId();
        if (!saleXiaoquService.hasSaleXiaoqu(xiaoquId, saleId)) {
            return AjaxMessage.newSuccessMsg();
        }
        saleXiaoquService.delete(xiaoquId, saleId);
        return AjaxMessage.newSuccessMsg();
    }
}
